﻿using BilbilDAL;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using Modles.DTO;
using Modles.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BilbilBLL
{
    public class PersonalHomepageFunctionServer
    {
        ReleaseVideoDAL dal = new ReleaseVideoDAL();
        DynamicDAL dynamicdal = new DynamicDAL();
        UserInfoDAL userInfoDAL = new UserInfoDAL();
        CollectionDAL collectionDAL  = new CollectionDAL();
        UploadVideoDAL uploadVideoDAL = new UploadVideoDAL();
        VideoTypeDAL videoTypeDAL = new VideoTypeDAL();
        ConcernDAL concernDAL = new ConcernDAL();
        /// <summary>
        /// 根据前端发送的用户信息表id查询并返回视频信息表，按视频发布时间降序排序，提供分页功能
        /// </summary>
        /// <param name="mod"></param>
        /// <param name="TotalCount"></param>
        /// <returns></returns>
        public ResponseTool GetReleaseVideoByuserId(int UserInfoId, int page, int limit)
        {
            if (UserInfoId == 0)
            {
                return ResponseTool.Fail("用户信息id不能为空");
            }
            if (page <= 0)
            {
                return ResponseTool.Fail("页码不能小于1");
            }
            List<VideoInfo_DTO> list = dal.GetReleaseVideoByuserId(UserInfoId, page, limit);
            return ResponseTool.Succeed(list);
        }
        /// <summary>
        /// 根据前端发送的用户信息表id查询并返回动态表，按发布时间降序排序
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ResponseTool GetDynamic(int userInfoId)
        {
            if (userInfoId == 0)
            {
                return ResponseTool.Fail("用户信息id不能为空");
            }
            List<Dynamic> list = dynamicdal.GetDynamic(userInfoId);
            ResponseTool res = ResponseTool.Succeed(list);
            return res;
        }

        /// <summary>
        /// 根据前端发送的用户信息表id查询并返回收藏表，按发布时间降序排序
        /// </summary>
        /// <param name="userInfoId"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public ResponseTool GetCollectionList(int userInfoId,int page, int limit, out int totalCount)
        { 
            totalCount = 0;
            if(page <= 0)
            {
                return ResponseTool.Fail("页码不能小于0");
            }
            List<VideoInfo_DTO> list = collectionDAL.GetCollectionList(userInfoId,page, limit, out totalCount);
            return ResponseTool.Succeed(list);
        }

        /// <summary>
        /// 根据前端发送的用户信息表id和用户信息修改用户信息
        /// </summary>
        /// <param name="modify_DTO"></param>
        /// <returns></returns>
        public ResponseTool UserinfoModify(UserInfoModify_DTO modify_DTO)
        {
            if (string.IsNullOrEmpty(modify_DTO.Name))
            {
                return ResponseTool.Fail("姓名不能为空");
            }
            if (string.IsNullOrEmpty(modify_DTO.Avatar))
            {
                return ResponseTool.Fail("头像不能为空");
            }
            if (string.IsNullOrEmpty(modify_DTO.Signature))
            {
                return ResponseTool.Fail("签名不能为空");
            }
            if(modify_DTO.Gender<0 || modify_DTO.Gender>2)
            {
                return ResponseTool.Fail("性别输入不正确");
            }
            if (string.IsNullOrEmpty(modify_DTO.Region))
            {
                return ResponseTool.Fail("地区不能为空");
            }



            var state = userInfoDAL.UserinfoModify(modify_DTO);
            if(state == 200)
            {
                return ResponseTool.Succeed("修改成功");
            }
            else if (state == 404)
            {
                return ResponseTool.Fail("没有找到该用户");
            }
            else
            {
                return ResponseTool.Fail("修改失败");
            }
        }
        /// <summary>
        /// 根据用户信息id获取用户关注人数和被关注人数
        /// </summary>
        /// <param name="UserInfoId"></param>
        /// <returns></returns>
        public ResponseTool GetConcernList(int UserInfoId)
        {
            if(UserInfoId == 0)
            {
                return ResponseTool.Fail("用户信息id不能为空");
            }
            return ResponseTool.Succeed(concernDAL.GetConcernList(UserInfoId));
        }
        public ResponseTool GetDataOverview(int UserInfoId)
        {
            UserInfoAll userInfoAll = new UserInfoAll();
            userInfoAll.Publish = new VideoInfoDAL().GetUserVideoCount(UserInfoId);
            userInfoAll.Comments = new CommentsDAL().GetUserCommentsCount(UserInfoId);

            return ResponseTool.Succeed(userInfoAll);
        }
        /// <summary>
        /// 上传视频
        /// </summary>
        /// <param name="videoData"></param>
        /// <param name="videoFile"></param>
        /// <param name="imageFile"></param>
        /// <returns></returns>
        public ResponseTool AddVideoInfo(VideoUpload_DTO videoData, IFormFile videoFile, IFormFile imageFile)
        {
            Response_DTO<VideoUploadResult_DTO> res = new Response_DTO<VideoUploadResult_DTO>();

            try
            {
                // 参数验证
                if (videoData == null){ return ResponseTool.Fail("视频数据不能为空");}
                if (string.IsNullOrEmpty(videoData.Title)){ return ResponseTool.Fail("视频标题不能为空");}
                if (videoData.UserInfoId <= 0) { return ResponseTool.Fail("用户信息错误");}
                if (videoData.VideoTypeId <= 0){return ResponseTool.Fail("视频类型不能为空");}
                if (videoFile == null || videoFile.Length == 0){return ResponseTool.Fail("请选择视频文件");}
                if (imageFile == null || imageFile.Length == 0){return ResponseTool.Fail("请选择封面图片");}

                // 验证文件大小
                if (videoFile.Length > 1024 * 1024 * 500) { return ResponseTool.Fail("视频文件不能超过500MB"); }

                if (imageFile.Length > 1024 * 1024 * 5) { return ResponseTool.Fail("封面图片不能超过5MB"); }

                // 验证文件类型
                var allowedVideoTypes = new[] { "video/mp4", "video/avi", "video/mov", "video/wmv" };
                var allowedImageTypes = new[] { "image/jpeg", "image/png", "image/gif", "image/jpg" };

                if (!allowedVideoTypes.Contains(videoFile.ContentType.ToLower())){ return ResponseTool.Fail("不支持的视频文件格式"); }

                if (!allowedImageTypes.Contains(imageFile.ContentType.ToLower())) { return ResponseTool.Fail("不支持的图片文件格式"); }

                // 检查用户和视频类型是否存在
                if (!userInfoDAL.IsUserExists(videoData.UserInfoId)){ return ResponseTool.Fail("用户不存在"); }
                if (!videoTypeDAL.IsVideoTypeExists(videoData.VideoTypeId)) { return ResponseTool.Fail("视频类型不存在"); }

                // 保存文件到服务器
                string videoPath = SaveFile(videoFile, "videos");
                string imagePath = SaveFile(imageFile, "images");

                if (string.IsNullOrEmpty(videoPath) || string.IsNullOrEmpty(imagePath)){ ResponseTool.Fail("文件保存失败"); }

                // 创建视频信息对象
                var videoInfo = new VideoInfo
                {
                    Title = videoData.Title,
                    Briefintroduction = videoData.Briefintroduction ?? "",
                    VideoTypeId = videoData.VideoTypeId,
                    UserInfoId = videoData.UserInfoId,
                    Label = videoData.Labels != null ? string.Join(",", videoData.Labels) : ""
                };

                // 添加到数据库
                int videoInfoId = uploadVideoDAL.AddVideoInfo(videoInfo, videoPath, imagePath);

                if (videoInfoId > 0)
                {
                    return ResponseTool.Succeed("上传成功");
                }
                else
                {
                    return ResponseTool.Fail("上传失败");
                }
            }
            catch (Exception ex)
            {
                return ResponseTool.Fail("上传过程中发生错误：" + ex.Message);
            }
        }
        /// <summary>
        /// 保存上传的文件
        /// </summary>
        /// <param name="file">上传的文件</param>
        /// <param name="folder">存储文件夹</param>
        /// <returns>文件存储路径</returns>
        private string SaveFile(IFormFile file, string folder)
        {
            try
            {
                // 创建存储目录
                var uploadsFolder = Path.Combine("wwwroot", "uploads", folder);
                if (!Directory.Exists(uploadsFolder))
                {
                    Directory.CreateDirectory(uploadsFolder);
                }

                // 生成唯一文件名
                var fileName = $"{Guid.NewGuid()}_{file.FileName}";
                var filePath = Path.Combine(uploadsFolder, fileName);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                // 返回相对路径
                return $"/uploads/{folder}/{fileName}";
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 根据用户信息id获取用户关注的视频数量
        /// </summary>
        /// <returns></returns>
        public ResponseTool GetUserCollectionCount(int userInfoId)
        {
            if (userInfoId <= 0)
            {
                return ResponseTool.Fail("用户信息Id不能为空");
            }
            return ResponseTool.Succeed(new CollectionDAL().GetUserCollectionCount(userInfoId));
        }
        /// <summary>
        /// 获取被关注的人员信息
        /// </summary>
        /// <param name="userInfoId"></param>
        /// <returns></returns>
        public ResponseTool GetConcernUserInfos(int userInfoId)
        {
            if (userInfoId == 0)
            {
                return ResponseTool.Fail("用户信息Id不能为空");
            }
            return ResponseTool.Succeed(new UserInfoDAL().GetConcernUserInfos(userInfoId));
        }


        /// <summary>
        /// 添加关注
        /// </summary>
        /// <param name="UserInfoId"></param>
        /// <param name="ConcernUserInfoId"></param>
        /// <returns></returns>
        public ResponseTool AddConcern(int UserInfoId, int ConcernUserInfoId)
        {
            if (UserInfoId == 0)
            {
                return ResponseTool.Fail("用户信息Id不能为空");
            }
            if (ConcernUserInfoId == 0)
            {
                return ResponseTool.Fail("被关注用户信息Id不能为空");
            }



            if(new CollectionDAL().AddCollectionInfo(UserInfoId, ConcernUserInfoId))
            {
                return ResponseTool.Succeed("关注成功");
            }
            else
            {
                return ResponseTool.Fail("关注失败");
            }
        }

        /// <summary>
        /// 取消关注
        /// </summary>
        /// <param name="UserInfoId"></param>
        /// <param name="ConcernUserInfoId"></param>
        /// <returns></returns>
        public ResponseTool DeleteConcern(int UserInfoId, int ConcernUserInfoId)
        {
            if (UserInfoId == 0)
            {
                return ResponseTool.Fail("用户信息Id不能为空");
            }
            if (ConcernUserInfoId == 0)
            {
                return ResponseTool.Fail("被关注用户信息Id不能为空");
            }

            if (new ConcernDAL().DeleteConcern(UserInfoId, ConcernUserInfoId))
            {
                return ResponseTool.Succeed("取关成功");
            } else
            {
                return ResponseTool.Fail("取关失败");
            }
        }

        /// <summary>
        /// 获取用户发布的所有视频
        /// </summary>
        /// <param name="userInfoId"></param>
        /// <returns></returns>
        public ResponseTool GetUserPublishVideoInfo(int userInfoId)
        {
            if(userInfoId == 0)
            {
                return ResponseTool.Fail("用户信息Id不能为空");
            }
            return ResponseTool.Succeed(new VideoInfoDAL().GetUserPublishVideoInfo(userInfoId));
        }


        /// <summary>
        /// 删除用户发布的指定视频
        /// </summary>
        /// <param name="userInfoId"></param>
        /// <param name="videoInfoId"></param>
        /// <returns></returns>
        public ResponseTool DeleteUserPublishVideoInfo(int userInfoId, int videoInfoId)
        {
            if (userInfoId == 0)
            {
                return ResponseTool.Fail("用户信息Id不能为空");
            }
            if (videoInfoId == 0)
            {
                return ResponseTool.Fail("视频信息Id不能为空");
            }

            if (new VideoInfoDAL().DeleteUserPublishVideoInfo(userInfoId, videoInfoId))
            {
                return ResponseTool.Succeed("删除成功");
            } else
            {
                return ResponseTool.Fail("删除失败");
            }
        }
    }
}
